//
//  DebitStyleView.swift
//  IDF
//
//  Created by 陈徐挺 on 24/03/2018.
//  Copyright © 2018 Jesse.chen. All rights reserved.
//

import UIKit
import Reusable
import EasyPeasy
import Dollar

class DebitStyleView: UIView, NibOwnerLoadable {

    @IBOutlet weak var titleImageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    var dataArr: [String] = []
    var buttonArr: [DebitStyleButton] = []
    var selectIndex: Int = 0
    var clickCallback : ((_ index : Int) -> Void)!

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.loadNibContent()
    }
    
    func refreshButton() {
        if let cb = clickCallback  {
            cb(selectIndex)
        }
        Dollar.each(buttonArr) { [weak self] (index, b) in
            if let this = self {
                b.setSelect(this.selectIndex)
            }
        }
    }

    func setView() {
        let width = (kWidth - 25 - 90) / 2
        let height = width * 100 / 260
        dataArr.forEach { [weak self] (string) in
            let b = DebitStyleButton(frame: CGRect(x: 0, y: 0, width: width, height: height))
            b.clickBtn.setTitle(string, for: .normal)
            b.clickCallback = { index -> Void in
                self?.selectIndex = index
                self?.refreshButton()
            }
            self?.addSubview(b)
            self?.buttonArr.append(b)
        }
        Dollar.each(buttonArr) { [weak self] (index, b) in
            b.index = index
            if let this = self {
                if index == 0 {
                    b <- [
                        Width(width),
                        Height(height),
                        Left(0).to(this.titleLabel, .left),
                        Top(20).to(this.titleLabel, .bottom),
                    ]
                } else if index % 2 == 1 {
                    let prevB = this.buttonArr[index - 1]
                    b <- [
                        Width(width),
                        Height(height),
                        Left(25).to(prevB, .right),
                        Top(0).to(prevB, .top),
                    ]
                } else {
                    let prevB = this.buttonArr[index - 2]
                    b <- [
                        Width(width),
                        Height(height),
                        Left(0).to(prevB, .left),
                        Top(20).to(prevB, .bottom),
                    ]
                }
            }
        }
    }
}
